import 'package:adb_tool/base/base_view_model.dart';
import 'package:adb_tool/page/home/menu_model.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:process_run/shell.dart';

import '../../common/app.dart';
import '../../ext/dialog_ext.dart';

class HomeViewModel extends BaseViewModel {
  /// 应用相关功能
  final List<MenuModel> categoryApps = [
    MenuModel(label: "安装应用", id: "installApp", hasChoose: true),
    MenuModel(label: "卸载应用", id: "unInstallApp", hasChoose: false),
    MenuModel(label: "启动应用", id: "startApp", hasChoose: false),
    MenuModel(label: "停止运行", id: "stopApp", hasChoose: false),
    MenuModel(label: "重启应用", id: "rebootApp", hasChoose: false),
    MenuModel(label: "清除数据", id: "clearData", hasChoose: false),
    MenuModel(label: "清除数据并重启应用", id: "clearDataAndRebootApp", hasChoose: false),
    MenuModel(label: "重置权限", id: "resetPermissions", hasChoose: false),
    MenuModel(label: "重置权限并重启应用", id: "resetPermissionsReboot", hasChoose: false),
    MenuModel(label: "授权所有权限", id: "setAllPermissions", hasChoose: false),
    MenuModel(label: "查看应用安装路径", id: "viewInstallPath", hasChoose: false),
  ];

  /// 系统相关功能
  final List<MenuModel> categorySystems = [
    MenuModel(label: "截图保存到电脑", id: "screenshotToPc", hasChoose: true),
    MenuModel(label: "开始录屏", id: "screenRecord", hasChoose: false),
    // MenuModel(label: "停止录屏幕并保存", id: "stopScreenRecord", hasChoose: false),
    MenuModel(label: "查看当前Activity", id: "viewCurrentActivity", hasChoose: false),
    MenuModel(label: "查看AndroidId", id: "viewApplicationId", hasChoose: false),
    MenuModel(label: "查看系统版本", id: "viewAndroidVersion", hasChoose: false),
    MenuModel(label: "查看IP地址", id: "viewLocalIdAddress", hasChoose: false),
    MenuModel(label: "查看蓝牙Mac地址", id: "viewLocalMacAddress", hasChoose: false),
    MenuModel(label: "重启手机", id: "rebootDevice", hasChoose: false),
  ];

  /// 按键相关
  final List<MenuModel> categoryActions = [
    MenuModel(label: "返回键", id: "backKeyword", hasChoose: false),
    MenuModel(label: "HOME键", id: "homeKeyword", hasChoose: false),
    MenuModel(label: "菜单键", id: "menuKeyword", hasChoose: false),
    MenuModel(label: "电源键", id: "powerKeyword", hasChoose: false),
    MenuModel(label: "增加音量", id: "volumeUpKeyword", hasChoose: false),
    MenuModel(label: "减少音量", id: "volumeDownKeyword", hasChoose: false),
    MenuModel(label: "静音", id: "volumeMuteKeyword", hasChoose: false),
    MenuModel(label: "切换应用", id: "switchAppKeyword", hasChoose: false),
    // MenuModel(label: "屏幕点击", id: "pressScreenKeyword", hasChoose: false),
  ];
  String deviceId;
  String packageName;

  ///录屏保存的文件名字
  var recordFileName = 'screenrecord${DateTime.now().millisecondsSinceEpoch}.mp4';

  /// 是否正在录屏
  var isRecording = false;
  String recordText = "开始录屏";

  HomeViewModel(BuildContext context, this.deviceId, this.packageName) : super(context);
  /// 有文件拖拽进来
  void onDragDone(DropDoneDetails details) {
    var files = details.files;
    if (files.isEmpty) {
      return;
    }
    for (var value in files) {
      if (value.path.endsWith(".apk")) {
        showAlertDialog(context: context, content: '是否安装${value.name}?',cancelText: "取消",onConfirm: (){
          installApk(deviceId, value.path);
        });
        // showInstallApkDialog(deviceId, value);
      }
    }
  }
  /// 选择文件安装应用
  void install() async {
    final typeGroup = XTypeGroup(label: 'apk', extensions: ['apk']);
    final file = await openFile(acceptedTypeGroups: [typeGroup]);
    installApk(deviceId, file?.path ?? "");
  }

  /// 卸载应用
  void uninstallApk() async {
    await App().getPackageName().then((value) => packageName = value);
    showAlertDialog(
        context: context,
        content: "你确定要删除包名为 " + packageName + " 吗？",
        cancelText: "取消",
        onConfirm: () async {
          var result = await execAdb([
            '-s',
            deviceId,
            'uninstall',
            packageName,
          ]);
          // getInstalledApp(deviceId);
          if (result != null && result.exitCode == 0) {
            App().eventBus.fire("refresh");
          }
          showResultDialog(
            content: result != null && result.exitCode == 0 ? "卸载成功" : "卸载失败",
          );
        });
  }

  /// 启动应用
  Future<void> startApp() async {
    /// 刷新时,包名更改了
    await App().getPackageName().then((value) => packageName = value);
    var launchActivity = await _getLaunchActivity();
    var result = await execAdb([
      '-s',
      deviceId,
      'shell',
      'am',
      'start',
      '-n',
      launchActivity,
    ]);
    showResultDialog(isSuccess: result != null && result.exitCode == 0);
  }

  /// 停止运行应用
  Future<void> stopApp({bool isShowResult = true}) async {
    await App().getPackageName().then((value) => packageName = value);
    var result = await execAdb([
      '-s',
      deviceId,
      'shell',
      'am',
      'force-stop',
      packageName,
    ]);
    if (isShowResult) {
      showResultDialog(isSuccess: result != null && result.exitCode == 0);
    }
  }

  /// 重启应用
  Future<void> restartApp() async {
    await stopApp(isShowResult: false);
    await startApp();
  }

  /// 清除数据
  Future<void> clearAppData() async {
    await App().getPackageName().then((value) => packageName = value);
    await execAdb([
      '-s',
      deviceId,
      'shell',
      'pm',
      'clear',
      packageName,
    ]);
  }

  /// 重置应用权限
  Future<void> resetAppPermission() async {
    var permissionList = await getAppPermissionList();
    for (var value in permissionList) {
      await execAdb([
        '-s',
        deviceId,
        'shell',
        'pm',
        'revoke',
        packageName,
        value,
      ]);
    }
  }

  /// 授予应用权限
  Future<void> grantAppPermission() async {
    var permissionList = await getAppPermissionList();
    for (var value in permissionList) {
      await execAdb([
        '-s',
        deviceId,
        'shell',
        'pm',
        'grant',
        packageName,
        value,
      ]);
    }
  }

  /// 获取应用安装路径
  Future<void> getAppInstallPath() async {
    var installPath = await execAdb([
      '-s',
      deviceId,
      'shell',
      'pm',
      'path',
      packageName,
    ]);
    if (installPath == null || installPath.outLines.isEmpty) {
      return;
    } else {
      var path = "";
      for (var value in installPath.outLines) {
        path += value.replaceAll("package:", "");
      }
      showResultDialog(
        content: path,
      );
    }
  }

  ///查看设备AndroidId
  Future<void> getAndroidId() async {
    var result = await execAdb([
      '-s',
      deviceId,
      'shell',
      'settings',
      'get',
      'secure',
      'android_id',
    ]);
    var outLines = result?.outLines;
    if (outLines == null || outLines.isEmpty) {
      showResultDialog(content: "没有AndroidId");
    } else {
      var androidId = outLines.first;
      showResultDialog(content: androidId);
    }
  }

  ///  查看设备系统版本
  Future<void> getDeviceVersion() async {
    var result = await execAdb(['-s', deviceId, 'shell', 'getprop', 'ro.build.version.release']);
    var result2 = await execAdb(['-s', deviceId, 'shell', 'getprop', 'ro.build.version.sdk']);
    showResultDialog(
      content: result != null && result.exitCode == 0
          ? ("Android " + result.stdout) + "\n" + ("Api " + result2?.stdout)
          : "获取失败",
    );
  }

  /// 查看设备IP地址
  Future<void> getDeviceIpAddress() async {
    var result = await execAdb([
      '-s',
      deviceId,
      'shell',
      'ifconfig',
      '|',
      'grep',
      'Mask',
    ]);
    var outLines = result?.outLines;
    if (outLines == null || outLines.isEmpty) {
      showResultDialog(content: "没有IP地址");
    } else {
      var ip = "";
      for (var value in outLines) {
        value = value.substring(value.indexOf("addr:"), value.length);
        ip += value.substring(0, value.indexOf(" ")) + "\n";
        print(value);
      }
      showResultDialog(content: ip);
    }
  }

  /// 查看设备Mac地址
  Future<void> getDeviceMac() async {
    // var result = await execAdb([
    //   '-s',
    //   deviceId,
    //   'shell',
    //   'cat',
    //   '/sys/class/net/wlan0/address',
    // ]);
    var result = await execAdb([
      '-s',
      deviceId,
      'shell',
      'settings',
      'get',
      'secure',
      'bluetooth_address',
    ]);
    showResultDialog(
      content: result != null && result.exitCode == 0 ? '蓝牙地址：' + result.stdout : result!.errText + "获取失败",
    );
  }

  /// 重启手机
  Future<void> reboot() async {
    var result = await execAdb([
      '-s',
      deviceId,
      'reboot',
    ]);
    showResultDialog(
      content: result != null && result.exitCode == 0 ? "重启成功" : "重启失败",
    );
  }

  /// 获取应用权限列表
  Future<List<String>> getAppPermissionList() async {
    await App().getPackageName().then((value) => packageName = value);
    var permission = await execAdb([
      '-s',
      deviceId,
      'shell',
      'dumpsys',
      'package',
      packageName,
    ]);
    if (permission == null) return [];
    var outLines = permission.outLines;
    List<String> permissionList = [];
    for (var value in outLines) {
      if (value.contains("permission.")) {
        var permissionLine = value.replaceAll(" ", "").split(":");
        if (permissionLine.isEmpty) {
          continue;
        }
        var permission = permissionLine[0];
        permissionList.add(permission);
      }
    }
    return permissionList;
  }

  /// 截图保存到电脑
  Future<void> screenshot() async {
    var path = await getDirectoryPath();
    if (path == null || path.isEmpty) return;
    var fileName = 'screenshot${DateTime.now().millisecondsSinceEpoch}.png';
    var result = await execAdb([
      '-s',
      deviceId,
      'exec-out',
      'screencap',
      '-p',
      '/sdcard/$fileName',
    ]);
    var result2 = await execAdb([
      '-s',
      deviceId,
      'pull',
      '/sdcard/$fileName',
      '$path/$fileName',
    ]);
    await   deleteFile("/sdcard/$fileName");
    if (result2 != null && result2.exitCode == 0) {
      showResultDialog(content: "截图保存成功");
    } else {
      showResultDialog(content: "截图保存失败");
    }

  }

  /// 录屏并保存到电脑
  Future<void> startScreenRecord() async {
    if (isRecording) {
      showAlertDialog(
          context: context,
          content: "正在录屏,是否停止当前录屏并保存",
          cancelText: "取消保存",
          onCancel: () {
            stopRecordAndSave(save: false);
          },
          onConfirm: () {
            stopRecordAndSave(save: true);
          });
      return;
    }
    recordFileName = 'screenrecord${DateTime.now().millisecondsSinceEpoch}.mp4';
    isRecording = true;
    notifyListeners();
    await shell.runExecutableArguments(adbPath, [
      '-s',
      deviceId,
      'shell',
      'screenrecord',
      '/sdcard/$recordFileName',
    ]);
  }

  /// 停止录屏
  Future<void> stopRecordAndSave({bool save = true}) async {
    shell.kill();
    isRecording = false;
    if (save) {
      var path = await getDirectoryPath();
      var pull = await execAdb([
        '-s',
        deviceId,
        'pull',
        '/sdcard/$recordFileName',
        '$path/$recordFileName',
      ]);
      await execAdb([
        '-s',
        deviceId,
        'shell',
        'rm',
        '/sdcard/$recordFileName',
      ]);
      if (pull != null && pull.exitCode == 0) {
        showResultDialog(content: "录屏保存成功");
      } else {
        showResultDialog(content: "录屏保存失败");
      }

    }

    notifyListeners();
    // deleteFile("/sdcard/$fileName");
  }

  /// Home键
  void pressHome() async {
    pressKey('3');
  }

  /// 菜单键
  void pressMenu() async {
    pressKey('82');
  }

  /// 返回键
  void pressBack() async {
    pressKey('4');
  }

  /// 增加音量
  void pressVolumeUp() async {
    pressKey('24');
  }

  /// 减少音量
  void pressVolumeDown() async {
    pressKey('25');
  }

  /// 静音
  void pressVolumeMute() async {
    pressKey('164');
  }

  /// 电源键
  void pressPower() async {
    pressKey('26');
  }

  /// 切换应用
  void pressSwitchApp() async {
    pressKey('187');
  }

  /// 按键点击事件
  void pressKey(String key) async {
    await execAdb([
      '-s',
      deviceId,
      'shell',
      'input',
      'keyevent',
      key,
    ]);
  }

  /// 获取启动Activity
  Future<String> _getLaunchActivity() async {
    await App().getPackageName().then((value) => packageName = value);
    var launchActivity = await execAdb([
      '-s',
      deviceId,
      'shell',
      'dumpsys',
      'package',
      packageName,
      '|',
      'grep',
      '-A',
      '1',
      'MAIN',
    ]);
    if (launchActivity == null) return "";
    var outLines = launchActivity.outLines;
    if (outLines.isEmpty) {
      return "";
    } else {
      for (var value in outLines) {
        if (value.contains("$packageName/")) {
          return value.substring(value.indexOf("$packageName/"), value.indexOf(" filter"));
        }
      }
      return "";
    }
  }
  /// 删除文件
  Future<void> deleteFile(String path) async {
    var result = await execAdb(["-s", deviceId, "shell", "rm", "-rf", path]);
    // if (result != null && result.exitCode == 0) {
    //   notifyListeners();
    //   showResultDialog(content: "删除成功");
    // } else {
    //   showResultDialog(content: "删除失败");
    // }
  }
}
